import os
import ckeynsecret

from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from myspace.myspaceapi import MySpace, MySpaceError
from oauthlib import oauth

class Friends(webapp.RequestHandler):
  def get(self):
    id = self.request.get('id')
    first = self.request.get('first')
    max = self.request.get('max')
    
    self.response.headers['Content-Type'] = 'application/json'
    
    try:
        int(id)
        int(first)
        int(max)
    except:
        err1 = {'errorCode':'invalidInput','errorMessage':'Invalid input'}
        self.response.out.write(simplejson.dumps(err1))
        return
    
    ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
    ms.token = oauth.OAuthToken('', '')
    
    try:
        friends = ms.get_friends(id, first, max)
    except MySpaceError, mse:
        err2 = {'errorCode':'invalidInput',
                'errorMessage':'Error fetching friend list'}
        self.response.out.write(simplejson.dumps(err2))
    
    self.response.out.write(simplejson.dumps(friends))
    

def main():
  application = webapp.WSGIApplication([
    ('/friends', Friends),
    ], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()